package com.edu.whty.common.tools;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Map工具类
 * @date 2014年11月17日
 */
public class MapUtils {
	
	private static Logger log = LoggerFactory.getLogger(MapUtils.class);
	
	/**
	 * 将对象转换为map,不存空值
	 * @param map 结果map集
	 * @param obj 目标对象
	 */
	public static void pullAll(Map<String,Object> map,Object obj){
		if(obj != null){
			Class<?> clazz = obj.getClass();
			putAll(map, obj, clazz);
		}
	}
	
	public static <K, V> Map<K,V> newHashMap(){
		return new HashMap<K, V>();
	}
	
	public static <K, V> Map<K,V> newLinkedHashMap(){
		return new LinkedHashMap<K, V>();
	}
	
	private static void putAll(Map<String,Object> map,Object obj,Class<?> clazz){
		Field[] fields = clazz.getDeclaredFields();
		for(Field field:fields){
			String fieldName = field.getName();
			if(!"serialVersionUID".equals(fieldName)){
				String getMethodName = "get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
				Method getMethod = null;
				try {
					getMethod = clazz.getDeclaredMethod(getMethodName, new Class[0]);
					if(!getMethod.isAccessible()){
						getMethod.setAccessible(true);
					}
					Object value = getMethod.invoke(obj, new Object[0]);
					if(value != null){
						map.put(fieldName, value);
					}
				} catch (NoSuchMethodException e) {
					log.error("NoSuchMethodException"+ e.getMessage());
				} catch (IllegalAccessException e) {
					log.error("IllegalAccessException"+e.getMessage());
				} catch (InvocationTargetException e) {
					log.error("InvocationTargetException"+e.getMessage());
				}
			}
		}
		//获取继承属性的值
		Class<?> superClazz = clazz.getSuperclass();
		if(superClazz != Object.class){
			putAll(map, obj, superClazz);
		}
	}

	public static void putAll(Map<String,Object> map, Object bean) {
		if (bean != null) {
			Class<?> clazz = bean.getClass();
			putAll(map, bean, clazz);
		}
	}
	
}
